package io.kimmking.rpcfx.client.netty_temp;
  
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;  
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder;

public class HttpClient {
    public void connect(String host, int port,HttpClientInboundHandler handler) throws Exception {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {  
                @Override  
                public void initChannel(SocketChannel ch) throws Exception {  
                    // 客户端接收到的是httpResponse响应，所以要使用HttpResponseDecoder进行解码  
                    ch.pipeline().addLast(new HttpResponseDecoder());
                    // 客户端发送的是httprequest，所以要使用HttpRequestEncoder进行编码  
                    ch.pipeline().addLast(new HttpRequestEncoder());
                    ch.pipeline().addLast(handler);
                }  
            });  
  

            ChannelFuture future = b.connect(host, port).sync();
            future.channel().closeFuture().sync();


        } finally {  
            workerGroup.shutdownGracefully();  
        }  
  
    }  
  
    public static void main(String[] args) throws Exception {
        HttpClientInboundHandler handler = new HttpClientInboundHandler();
        new Thread(()->{
            HttpClient httpClient = new HttpClient();
            try {
                httpClient.connect("127.0.0.1", 8844,handler);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("client end");

        }).start();
        Thread.sleep(1000);
        String ret = handler.sendMessage("hello?");
        System.out.println(ret);
        ret = handler.sendMessage("hello?");
        System.out.println(ret);
    }  
}